package com.seqb.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seqb.manage.user.dao.UserDao;
import com.seqb.manage.user.domain.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/26
 */
@Component
public class ShiroUtils {

    private static UserDao userDao;

    public ShiroUtils(UserDao userDao) {
        this.userDao = userDao;
    }

    public static Subject getSubjct() {
        Subject subject = null;
        try {
            subject = SecurityUtils.getSubject();
        } catch (Exception e) {
        }
        return subject;
    }

    public static UserDO getUser() {
        if (null != getSubjct() && null != getSubjct().getPrincipal()) {
            String account = JwtUtils.getAccount(getSubjct().getPrincipal().toString());
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("account", account);
            return userDao.selectOne(queryWrapper);
        }
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            String account = JwtUtils.getAccount(token);
            if (!StringUtils.isEmpty(account)) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("account", account);
                UserDO user = userDao.selectOne(queryWrapper);
                int verify = JwtUtils.verify(token, account, user.getPassword());
                if (verify == 1) {
                    return user;
                }
            }
        }
        return null;
    }


}
